package crud

import (
	"fmt"
	"os"
	"strings"

	"cms/system/helper"
)

var cTempl = `<?php
namespace {{.__NAMESPACE__}};

use think\Exception;
use laytp\controller\Backend;
use think\facade\Config;
use think\facade\Db;
use laytp\library\CommonFun;
use {{.__ADDVALIDATE__}};
use {{.__EDITVALIDATE__}};
use {{.__FULLMODEL__}} as {{.__CLASS__}}Model;

class {{.__CLASS__}} extends Backend
{

    /**
     * member模型对象
     * @var {{.__CLASS__}}Model
     */
    protected $model;
	protected $hasSoftDel = {{.__SELFDELETE__}};//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = []; // 无需鉴权即可请求的方法

    public function _initialize()
    {
        $this->model = new {{.__CLASS__}}Model();
    }

    
    //查看和搜索列表
    public function index(){
        $where  = $this->buildSearchParams();
        $order  = $this->buildOrder();
        $data   = $this->model->where($where)->order($order){{.__WITH__}};
        $paging = $this->request->param('paging', false);
        if ($paging) {
            $limit        = $this->request->param('limit', Config::get('paginate.limit'));
            $data         = $data->paginate($limit)->toArray();
            $data['data'] = $this->getSelectedData($data['data']);
        } else {
            $data = $data->select()->toArray();
        }
        return $this->success('获取成功', $data);
    }

    
    //添加
    public function add()
    {
        Db::startTrans();
        try {
            $post = CommonFun::filterPostData($this->request->post());
            $validate = new Add();
            if(!$validate->check($post)){
                throw new Exception($validate->getError());
            }
			if (isset($post['laytpUploadFile'])) {
	            unset($post['laytpUploadFile']);
	        }
            $post['create_time'] = date('y-m-d H:i:s');
            $post['update_time'] = date('y-m-d H:i:s');

            if (!$this->model->insert($post)) {
                throw new Exception("添加信息失败");
            }

            Db::commit();

            return $this->success('操作成功');
        } catch (Exception $e) {
            Db::rollback();

            return $this->error($e->getMessage());
        }
    }

    
    //查看详情
    public function info()
    {
        $id   = $this->request->param('id', 0, 'intval');
        if (!$id) {
            return $this->error("缺少id");
        }
        $obj = $this->model->find($id);
        if (!$obj) {
            return $this->error("记录不存在");
        }
        $info = $obj->toArray();

        return $this->success('获取成功', $info);
    }

    
    //编辑
    public function edit(){
        Db::startTrans();
        try {
            $id = $this->request->param('id', 0, 'intval');
            $info = $this->model->find($id);
            if (!$info) {
                throw new Exception("该记录不存在");
            }

            $post = CommonFun::filterPostData($this->request->post());
            $validate = new Edit();
            if(!$validate->check($post)){
                throw new Exception($validate->getError());
            }
			if (isset($post['laytpUploadFile'])) {
	            unset($post['laytpUploadFile']);
	        }

            foreach ($post as $k => $v) {
                $info->$k = $v;
            }
            $info->update_time = date('y-m-d H:i:s');

            if (false === $info->save()) {
                throw new Exception("操作失败");
            }

            Db::commit();

            return $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();

            return $this->error($e->getMessage());
        }
    }

    //设置状态
    public function setStatus()
    {
        $id       = $this->request->post('id');
        $status = $this->request->post('field_val');

        Db::startTrans();
        try {
            $updateRes = $this->model->where('id', $id)->save(['status' => $status]);
            if (false === $updateRes) {
                return new Exception("修改失败");
            }

            Db::commit();

            return $this->success('操作成功');
        } catch (\Exception $e) {
            Db::rollback();

            return $this->error($e->getMessage());
        }
    }
}`

// 生成控制器
func (g *cGlobal) MakeController() error {
	nName := g.AppPath.ControllerPath
	err := os.MkdirAll(nName, os.ModePerm)
	if err != nil {
		return err
	}
	__WITH__ := ""
	if g.Field != nil {
		withs := make([]string, 0)
		if _, ok := g.Field["user_id"]; ok {
			withs = append(withs, "members")
		}
		if _, ok := g.Field["level_id"]; ok {
			withs = append(withs, "levels")
		}
		if _, ok := g.Field["book_id"]; ok {
			withs = append(withs, "books")
		}
		if _, ok := g.Field["order_id"]; ok {
			withs = append(withs, "orders")
		}
		if _, ok := g.Field["shop_id"]; ok {
			withs = append(withs, "shops")
		}
		if _, ok := g.Field["thumb_id"]; ok {
			withs = append(withs, "thumbs")
		}
		if _, ok := g.Field["article_id"]; ok {
			withs = append(withs, "articles")
		}
		if _, ok := g.Field["category_id"]; ok {
			withs = append(withs, "categorys")
		}
		if len(withs) > 0 {
			__WITH__ = fmt.Sprintf("->with([\"%s\"])", join("\",\"", withs...))
		} else {
			__WITH__ = ""
		}

	}

	cinx := strings.LastIndex(g.TableName, "_")
	lowerClassName := g.TableName[cinx+1:]
	className := helper.UcFirst(lowerClassName)
	m := map[string]string{
		"__NAMESPACE__":    g.NameSpace.Controller,
		"__ADDVALIDATE__":  g.AppClass.ValidateAdd,
		"__EDITVALIDATE__": g.AppClass.ValidateEdit,
		"__FULLMODEL__":    g.AppClass.Model,
		"__CLASS__":        className,
		"__MODEL__":        className,
		"__SELFDELETE__":   "0",
		"__WITH__":         __WITH__,
	}

	err = TemplateExec(g.AppFiles.Controller, cTempl, m)
	if err != nil {
		return err
	}

	return nil
}
